package base.aop;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import base.anno.Logger;
import base.entity.Log;
import base.entity.User;
import base.service.sys.LogService;
import base.util.IpUtil;

/**
 * 
 * LoggerAdvice
 *
 * @author 姜治昊
 * @time 2018年2月1日 下午9:55:14
 */
@Aspect    
@Component
public class LoggerAdvice {

	@Autowired
	private LogService logService;
	
	/**
	 * 用户动作
	 * execution(* bs.service.*.*(..))
	 */
	@Pointcut("@annotation(base.anno.Logger)")
	public void logAdvice(){}
	
	/**
	 * 登录
	 */
	@Pointcut("@annotation(base.anno.LoginLogger)")
	public void loginLogAdvice(){}
	
	/**
	 * 登录日志
	 */
	@After("loginLogAdvice()")
	public void loginAdvice(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		User user = (User) request.getSession().getAttribute("LOGIN_USER");
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		Log log = new Log("用户登录", "用户登录", new Date(), method.getName(), user, IpUtil.getIpAddress(request));
		if(null == user || null == user.getId() || user.getId() <= 0) {
			log.setDescription("登录失败");
		} else {
			log.setDescription("登录成功");
		}
		logService.saveLog(log);
	}
	
	/**
	 * 已经的登陆用户的动作日志
	 * @param joinPoint
	 */
	@Before("logAdvice()")
	public void requestAdvice(JoinPoint joinPoint) {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		User user = (User) request.getSession().getAttribute("LOGIN_USER");
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		Logger logger = method.getAnnotation(Logger.class);
		String description = logger.description();
		Log log = new Log("动作日志", description, new Date(), method.getName(), user, IpUtil.getIpAddress(request));
		logService.saveLog(log);
	}

}
